package com.dream.utils.cookie;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.dream.utils.system.cfg.SystemConfigUtils;
/**
 * 
 * @author Evan
 * @date 2013/8/25
 *
 */
public class CookieUtils {
	
	 //default set the expire time of cookie is 1 week
	private static final String COOKIE_EXPIRE_TIME = "cookie.expire.time";
	
	public static void addCookie(HttpServletResponse response,HttpServletRequest request,String name,String value){
	  
		Cookie cookie = new Cookie(name,value);
	    cookie.setPath("/");
	    int expireTime = SystemConfigUtils.instance().getInteger(COOKIE_EXPIRE_TIME, 604800);
	    cookie.setMaxAge(expireTime);
	    response.addCookie(cookie);
	    
	}
	
	public static void removeCookie(HttpServletResponse response,HttpServletRequest request,String name){
		
		Cookie cookie = getCookieByName(request,name);
		if(cookie != null){
			cookie.setValue(null);
			cookie.setPath("/");
		    cookie.setMaxAge(0);
		    response.addCookie(cookie);
		}
	}
	public static Cookie getCookieByName(HttpServletRequest request,String name){
		
		if(StringUtils.isBlank(name)){
			return null;
		}
		
	    Cookie[] cookies = request.getCookies();
	    if(cookies != null){
	        for(Cookie cookie : cookies){
	            if(name.equals(cookie.getName())){
	            	return cookie;
	            }
	        }
	    }
	    return null;
	}
	
	public static String getCookieValueByName(HttpServletRequest request,String name){
	
		String value = null;
		Cookie cookie = getCookieByName(request,name);
		if(cookie != null){
			value = cookie.getValue();
		}
		return value;
		
	}
}
